/* Soundplayer
 * written by timothy3592 and x0thatguy0x
 * August 10, 2012
 */
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <unistd.h>
#include <dlfcn.h>

//do my includes
#include "../include/soundplayer.h"
#include "../include/decodemodules.h"
#include "../include/soundplayer_filters.h"

environment_t env;

/*
typedef struct _playlist {
	int num_songs;
	int cur_song;
	char **song_list;
	void (*append)(char *filename);
} playlist;
*/


int check_input(int fd){
	struct stat file_info;

	fstat(fd, &file_info);   //get file info
	env->size = (unsigned long) file_info.st_size;

	int ret = 0;

	//conditional statements
	if (S_ISREG(file_info.st_mode)) {
		ret = 1;
	}
	else if (S_ISFIFO(file_info.st_mode)) {
		env->size = BUF_SIZE;
		ret = 2;
	}
	else {
		env->message("Input file was not a file or a pipe\n");
	}
	return ret;
}


int main(int argc, char** argv) {
	char *song_name;
	FILE* input;
	void (*play[5])(FILE *song); //array of function pointers
	play[TYPE_WAVE] = play_wav;
	play[TYPE_MP3] = play_mp3;
	play[TYPE_OGG] = play_ogg;
	play[TYPE_AAC] = play_aac;
	play[TYPE_FLAC] = play_flac;

	if (argc <= 1){
		help();
		return 1;
	}

	if (arg_parse(argc, argv) != 0) return 1;

	while (optind < argc) {
		song_name = argv[optind++]; //choose a song
		input = (*song_name == '-')? stdin : fopen(song_name, "rb");

		if (input == NULL){
			//opening input failed
			perror(NULL); //this displays a more informative message
			return 1;
		}

		env->isfifo = check_input(fileno(input));
		if(FLAGUNSET(SP_OVERRIDE_FORMAT))
			env->format = qualify_filename(song_name);
		env->message("Now Playing %s\n", song_name); //I just set this to printf... looking to the future

		if ((pcm_output_init() == 0 ) && env->isfifo != 0 && env->format >=0 ) play[env->format](input);

		pcm_output_term(); //destroy sound
		fclose(input);   //close input
	}

	//FIXME: doing argument parsing this way prevents dlclose()-ing this
	//if (env->use_filter == 1) dlclose(plugin_handle);

	return 0;
}
